<template>
  <div class="tw-applistbox">
    <!-- 分页按钮 -->
    <div v-if="!disablePagination"
      class="tw-applist-pagination">
      <i class="icon iconfont"
        :class="{xdisabled: pageNo<=1}"
        @click="(pageNo>1 && (pageNo--))">&#xe7db;</i>
      <i class="icon iconfont"
        :class="{xdisabled: pageNo>=appList.length/showCounts}"
        @click="(pageNo<appList.length/showCounts && (pageNo++))">&#xe7dc;</i>
    </div>
    <!-- 分页按钮 -->

    <!-- 列表栏 -->
    <div v-if="list && list.length>0"
      class="tw-applist">
      <a class="tw-applist-item"
        @click="appEnter(app)"
        :class="{xisrepeat: app.isRepeat}"
        :style="{width: `calc((100% - ${(columns - 1)} * ${itemSpacing}) / ${columns})`}"
        v-for="(app, idx) in list"
        :key="idx">
        <div class="tw-applist-item-iconbox">
          <img v-if="app.img"
            :src="app.img.startsWith('http')?app.img:`${$twApp.gateway}/fs/media${app.img}`" />
          <img v-else-if="appImages[idx]"
            :src="`${$twApp.fileBaseUrl}${appImages[idx].localPath}`" />
          <img v-else
            src="@assets/app-default.png" />
        </div>

        <div class="tw-applist-item-body">
          <h4>{{app.name}}</h4>
          <div>
            <span>进入</span>
            <i></i>
          </div>
        </div>
      </a>
    </div>
    <!-- 列表栏 -->
    <tw-lib-nodata v-else />

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible"
      :class="`tw-libbutton x${_uid}`"
      class="tw-apps"
      :close-on-click-modal="false"
      :show-close="true"
      :before-close="handleClose"
      :append-to-body="true">
      <div slot="title">
        <p class="xtitle-top">{{dialogTitleText}}</p>
      </div>
      <div class="tw-apps-body">
        <p>您将跳转至第三方服务平台：</p>
        <p class="xpath-tips"
          style="-webkit-box-orient: vertical">
          {{otherAppPath + '，' + otherAppName}}
        </p>
        <p>请您注意个人信息及财产安全，使用中如遇到问题请及时与我们联系。</p>
        <div class="xlink-info">
          <span class="xtag">咨询电话：</span>
          <p v-html="innerText"
            class="xinner"></p>
        </div>
      </div>
      <div slot="footer"
        class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary"
          @click="handleClose('toApp')">继续访问</el-button>
      </div>
    </el-dialog>
    <!-- 弹窗 -->
  </div>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'
import nodata from '../tw-lib-base/no-data/no-data'
import padding from '../tw-lib-base/padding/mixins'
export default {
  name: 'table',
  mixins: [style, nodata, padding],
  props,

  data() {
    return {
      appList: [],
      pageNo: 1,
      dialogVisible: false,
      otherAppName: '',
      otherAppPath: '',
      innerText: '',
      currentApp: {},
      curOtherAppList: [
        '北京数字学校',
        '问卷调查',
        '东城教育信息化统一服务平台',
        '东城区初中化学自主学习平台',
        '东城区初中地理选考复习平台',
        '东城区消息中心',
        '运维中心',
        '统一门户平台',
        '东城-个人空间',
        '数据主题门户',
        '数据可视化管理系统',
        '东城区智慧教育云服务大屏'
      ]
    }
  },

  computed: {
    list() {
      let result = []

      if (this.showCounts) {
        result = this.appList.filter(
          (item, idx) =>
            (this.pageNo - 1) * this.showCounts <= idx &&
            idx < this.pageNo * this.showCounts
        )
      } else {
        result = this.appList
      }

      let blank = result.length % parseInt(this.columns)

      if (blank > 0) {
        blank = parseInt(this.columns) - blank

        if (result.length > 0) {
          const repeatApp = JSON.parse(
            JSON.stringify(result[result.length - 1])
          )
          repeatApp.isRepeat = true
          result.length += blank
          result.fill(repeatApp, result.length - blank)
        }
      }

      return result
    },

    style() {
      return Object.assign(
        {
          borderColor: this.borderColor,
          borderRadius: this.borderRadius,
          iconSize: this.iconSize,
          nameFontSize: this.nameFontSize,
          nameColor: this.nameColor,
          linkFontSize: this.linkFontSize,
          linkColor: this.linkColor,
          hoverColor: this.hoverColor,
          paginationColor: this.paginationColor,
          paginationSize: this.paginationSize,
          paginationHoverColor: this.paginationHoverColor,
          borderShadow: this.borderShadow,
          dialogShow: this.dialogShow,
          appDialogImg: this.appDialogImg,
          dialogTitleColor: this.dialogTitleColor,
          dialogTopicColor: this.dialogTopicColor,
          dialogTopicColorHover: this.dialogTopicColorHover,
          textInnerColor: this.textInnerColor
        },
        this.paddingStyle
      )
    }
  },

  methods: {
    setStyle() {
      let style = ''

      if (this.borderColor) {
        style += `
          ::root .tw-applist {
            border-top: 1px solid ${this.borderColor};
            border-left: 1px solid  ${this.borderColor};
          }

          ::root .tw-applist-item {
            border-right: 1px solid  ${this.borderColor};
            border-bottom: 1px solid  ${this.borderColor};
          }
        `
      }

      if (this.borderShadow) {
        style += `
        ::root .tw-applist-item {
          box-shadow: 0 0px 10px 0 rgba(201,215,224,0.5);
        }

         ::root .tw-applist-item:hover {
          box-shadow: 0 0px 20px 0 rgba(201,215,224,1)
        }
        `
      }

      style += `
        ::root .tw-applist-item {
          border-radius: ${this.borderRadius};
           padding: ${this.paddingTop} ${this.paddingRight} ${this.paddingBottom} ${this.paddingLeft};
        }

        ::root .tw-applist-item-iconbox {
          width: ${this.iconSize};
          min-width: ${this.iconSize};
          height:${this.iconSize};
        }

        ::root .tw-applist-item-body > h4 {
          font-size: ${this.nameFontSize};
          color: ${this.nameColor};
        }

        ::root .tw-applist-item-body > div {
          font-size: ${this.linkFontSize};
          color: ${this.linkColor};
        }

        ::root .tw-applist-item-body > div > i {
          border-right-color: ${this.linkColor};
          border-bottom-color: ${this.linkColor};
        }

        ::root .tw-applist-item:hover .tw-applist-item-body > h4,
        ::root .tw-applist-item:hover .tw-applist-item-body > div {
          color: ${this.hoverColor};
        }

        ::root .tw-applist-item:hover .tw-applist-item-body > div > i  {
          border-right-color: ${this.hoverColor};
          border-bottom-color: ${this.hoverColor};
        }

        ::root .tw-applist-pagination .iconfont {
          color: ${this.paginationColor};
          font-size: ${this.paginationSize};
        }

        ::root .tw-applist-pagination .iconfont:hover {
          color: ${this.paginationHoverColor};
        }

        ::root.el-dialog__wrapper.tw-apps .el-dialog .xtitle-top {
          color: ${this.dialogTitleColor}
        }

        ::root.el-dialog__wrapper.tw-apps .el-dialog .xpath-tips {
          color: ${this.dialogTopicColor}
        }

        ::root.el-dialog__wrapper.tw-apps .el-dialog .xinner {
          color: ${this.textInnerColor}
        }

        ::root.el-dialog__wrapper.tw-apps .el-button:focus,
        ::root.el-dialog__wrapper.tw-apps .el-button {
          color: ${this.dialogTopicColor}
        }

        ::root.el-dialog__wrapper.tw-apps .el-button:focus,
        ::root.el-dialog__wrapper.tw-apps .el-button:hover {
          background-color: #fff;
          border-color: ${this.dialogTopicColor}
        }

        ::root.el-dialog__wrapper.tw-apps .el-button--primary:focus,
        ::root.el-dialog__wrapper.tw-apps .el-button--primary {
          color: #fff;
          background-color: ${this.dialogTopicColor};
          border: 1px solid ${this.dialogTopicColor}
        }

        ::root.el-dialog__wrapper.tw-apps .el-button--primary:focus:hover,
        ::root.el-dialog__wrapper.tw-apps .el-button--primary:hover {
          color: #fff;
          background-color: ${this.dialogTopicColorHover};
          border: 1px solid ${this.dialogTopicColorHover}
        }
      `
      if (this.appDialogImg.length > 0) {
        style += `
          ::root.el-dialog__wrapper.tw-apps .el-dialog .el-dialog__header {
            background: url('${
              this.$twApp.fileBaseUrl + this.appDialogImg[0].localPath
            }') no-repeat center;
            background-size:100% 100%
          }

          ::root.el-dialog__wrapper.tw-apps .el-icon-close:before {
            color: #fff;
          }
        `
      }

      this.addStyle(style)
    },

    appEnter(app) {
      const vm = this
      // 区分当前应用是否为第三方，只有第三方应用才会弹窗（目前以名称过滤掉）
      let isOtherApp = false
      const isExist = this.curOtherAppList.indexOf(app.name)
      if (isExist !== -1) {
        isOtherApp = true
      }

      if (vm.dialogShow && !isOtherApp) {
        vm.currentApp = app
        vm.otherAppPath = app.url
        vm.otherAppName = app.name
        vm.innerText = app.inner
        vm.dialogVisible = true
      } else {
        const toHref = `${app.url || '#'}${
          app.addAccreditCode
            ? (app.url && app.url.includes('?') ? '&' : '?') +
              this.$twApp.user.accreditUrl
            : ''
        }`
        window.open(toHref, '_blank')
      }
    },

    handleClose(item) {
      const vm = this
      vm.dialogVisible = false
      if (item === 'toApp') {
        const href = `${vm.currentApp.url || '#'}${
          vm.currentApp.addAccreditCode
            ? (vm.currentApp.url && vm.currentApp.url.includes('?')
                ? '&'
                : '?') + vm.$twApp.user.accreditUrl
            : ''
        }`
        window.open(href, '_blank')
      }
      vm.otherAppName = ''
      vm.otherAppPath = ''
      vm.innerText = ''
      vm.currentApp = {}
    },

    getAppList() {
      // window.axios.defaults.headers.common['Access-Token'] = '6b3188767e8b26bd666a287f5acab9ca'
      // window.axios.defaults.headers.common['Current-Org-Id'] = '2111000684'
      // window.axios.defaults.headers.common['Tenant-Id'] = 'e000052'

      window.axios
        .post(`${window.$twApp.gateway}/openapi-uc/app/recommend/list`, {})
        .then((resp) => {
          if (
            resp.data.serverResult.resultCode &&
            resp.data.pageInfo &&
            resp.data.pageInfo.list
          ) {
            this.appList = resp.data.pageInfo.list.map((item, idx) => {
              return {
                id: item.appId,
                name: item.appName,
                url: item.callbackUrl || item.domain,
                addAccreditCode: true,
                img: item.icon1
                  ? `${this.$twApp.gateway}/fs/media${item.icon1}`
                  : '',
                inner: item.description.replace(/\n/g, '<br />')
              }
            })
          } else {
            this.$ui.msg({
              type: 'error',
              message: '错误应用列表失败'
            })
          }
        })
        .catch((e) => {
          this.$ui.msg({
            type: 'error',
            message: '错误应用列表失败'
          })
        })
    }
  },

  created() {
    window.ddd = this
    if (this.appType === '1') {
      this.getAppList()
    } else {
      this.appList = this.data
    }
  },

  watch: {
    appType(val) {
      if (val === '1') {
        this.getAppList()
      } else {
        this.appList = this.data
      }
    },

    data: {
      deep: true,
      handler() {
        this.appList = this.data
      }
    }
  }
}
</script>

<style lang="scss">
@import './css/index.scss';
</style>
